package com.example.ruleenginedrools.rule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ruleenginedrools.entity.RuleDomain;
import com.example.ruleenginedrools.service.impl.RulesServiceImpl;
import org.kie.api.KieBase;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.sql.Timestamp;


/**
 * @author zhangyunzhe
 */
@Configuration
public  class RuleExecutor {
    protected static volatile RuleDomain rule;
    protected RulesServiceImpl ruleService;
    protected KieHelper kieHelper;
    protected KieBase kieBase;

    @Autowired
    public RuleExecutor(RulesServiceImpl rulesService){
        this.ruleService=rulesService;
         kieHelper = new KieHelper();
    }

    public void judge(String queue, Object... facts) {
        refreshRules("name",queue);
        StatelessKieSession kieSession = kieBase.newStatelessKieSession();
        for (Object fact : facts) {
            kieSession.execute(fact);
        }
    }

    /**
     * 刷新规则（临时）
     * 这种做法在每次判断规则前都检测是否有刷新，正常应该被动刷新，不用主动检测
     */

    public void refreshRules(String column, String value) {
        if (rule == null) {
            synchronized (this) {
                rule = ruleService.getOne(new QueryWrapper<RuleDomain>()
                        .eq(column, value));
                kieHelper.addContent(rule.getDrlContent(), ResourceType.DRL);
                kieBase = kieHelper.build();
            }
        } else {
            Timestamp updateTime = ruleService.getObj(new QueryWrapper<RuleDomain>().eq(column, value).select("update_time"), o -> (Timestamp) o);
            if (!updateTime.equals(rule.getUpdateTime())) {
                synchronized (this) {
                    rule = ruleService.getOne(new QueryWrapper<RuleDomain>()
                            .eq(column, value));
                    kieHelper = new KieHelper();
                    kieHelper.addContent(rule.getDrlContent(), ResourceType.DRL);
                    kieBase = kieHelper.build();
                }
            }
        }
    }
}
